package com.bw.day1homework

import androidx.compose.material3.Icon
import androidx.compose.material3.NavigationBar
import androidx.compose.material3.NavigationBarItem
import androidx.compose.material3.Scaffold
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.ui.res.painterResource
import androidx.navigation.NavDestination.Companion.hierarchy
import androidx.navigation.NavGraph.Companion.findStartDestination
import androidx.navigation.NavHostController
import androidx.navigation.compose.currentBackStackEntryAsState
import androidx.navigation.compose.rememberNavController
import com.bw.lib_common.NavPath

sealed class MainItem(val path: String, val img: Int, val title: String) {
    object homeNav : MainItem(NavPath.HOME, R.drawable.ic_home, "首页")
    object cinemaNav : MainItem(NavPath.CINEMA, R.drawable.ic_cinema, "放映")
    object publishNav : MainItem(NavPath.PUBLISH, R.drawable.ic_send, "发布")
    object liveNav : MainItem(NavPath.LIVE, R.drawable.ic_live, "直播")
    object mineNav : MainItem(NavPath.MINE, R.drawable.ic_mine, "我的")
}

@Composable
fun MainPage(navHostController: NavHostController = rememberNavController()) {
    val listOf = listOf(
        MainItem.homeNav,
        MainItem.cinemaNav,
        MainItem.publishNav,
        MainItem.liveNav,
        MainItem.mineNav
    )
    val navBackStackEntry by navHostController.currentBackStackEntryAsState()
    val navDestination = navBackStackEntry?.destination

    Scaffold(bottomBar = {
        if (navDestination?.hierarchy?.any { listOf.map { it.path }.contains(it.route) } == true) {
            NavigationBar {
                listOf.forEach { nav ->
                    NavigationBarItem(
                        selected = navDestination?.hierarchy?.any { it.route == nav.path } == true,
                        onClick = {
                            navHostController.navigate(nav.path) {
                                popUpTo(navHostController.graph.findStartDestination().id) {
                                    saveState = true
                                }
                                launchSingleTop = true
                                restoreState = true
                            }
                        },
                        icon = {
                            Icon(painter = painterResource(id = nav.img), contentDescription = "")
                        }, label = { Text(text = nav.title) })
                }
            }
        }
    }) {
        NavPage(navHostController = navHostController, paddingValues = it)
    }

}